package com.my.juc.test;

import java.util.LinkedList;

/**
 * @author zhupanlin
 * @version 1.0
 * @description: TODO
 * @date 2024/4/24 15:25
 */
// 消息队列类，java线程之间通信
public class MessageQueue {

    public static void main(String[] args) {
        MessageQueue queue = new MessageQueue(2);
        for (int i = 0; i < 3; i++) {
            int id = i;
            new Thread(() -> {
                queue.put(new Message(id, "值" + id));
            }, "生产者" + i).start();
        }
        
        new Thread(() -> {
            try {
                while (true) {
                    Thread.sleep(1000);
                    Message message = queue.take();
                }
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
            
        }, "消费者").start();
    }
    
    // 消息队列
    private LinkedList<Message> list = new LinkedList<>();
    // 队列容量
    private int capacity;

    public MessageQueue(int capacity) {
        this.capacity = capacity;
    }

    // 获取消息
    public Message take() {
        // 检查对象是否为空
            synchronized (list) {
                while (list.isEmpty()) {
                    try {
                        System.out.println("队列为空,消费者线程等待" + Thread.currentThread().getName());
                        list.wait();
                    } catch (InterruptedException e) {
                        throw new RuntimeException(e);
                    }
                }
                // 从队列头部获取消息并返回
                Message message = list.removeFirst();
                System.out.println("已消费消息:" + message);
                list.notifyAll();
                return message;
            }
    }
    
    // 存入消息
    public void put(Message message) {
        synchronized (list) {
            // 检查队列是否已满
            while (list.size() == capacity) {
                try {
                    System.out.println("队列已满,生产者线程等待" + Thread.currentThread().getName());
                    list.wait();
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
            // 将消息加入队列尾部
            list.addLast(message);
            System.out.println("已生产消息:" + message);
            list.notifyAll();
        }
    }
    
}

final class Message {
    private int id;
    private Object value;

    public Message(int id, Object value) {
        this.id = id;
        this.value = value;
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public Object getValue() {
        return value;
    }

    public void setValue(Object value) {
        this.value = value;
    }

    @Override
    public String toString() {
        return "Message{" +
                "id=" + id +
                ", value=" + value +
                '}';
    }
}
